import { CreateResoruceDto } from './dto/createaResource.dto';
import { ResourceEntity } from './../../entity/video-resource.entity';
import { CreateVideoDto } from './dto/createVideo.dto';
import { CommonRepService } from './../../common/services/commonRep.service';
import { VideoEntity } from './../../entity/video.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MaxKey, Repository } from 'typeorm';

@Injectable()
export class VideoService extends CommonRepService<VideoEntity, CreateVideoDto>{
    constructor(
        @InjectRepository(VideoEntity) private readonly videoRep: Repository<VideoEntity>,
        @InjectRepository(ResourceEntity) private readonly resourceRep: Repository<ResourceEntity>
    ) {
        super(videoRep);
    }

    async queryDetail(id: string): Promise<any> {
        const one = await this.findOneById(id);
        const types: any[] = await this.resourceRep
            .createQueryBuilder('r')
            .where('videoId = :id', { id })
            .groupBy('r.sourceType')
            .getMany();

        for (const item of types) {
            const list = await this.resourceRep.find({
                where: {
                    sourceType: item.sourceType,
                    videoId: id
                },
                order: {
                    sort: 'ASC'
                }
            })
            one[item.sourceType] = list;
        }
        return one;
    }

    async addResource(dto: CreateResoruceDto) {
        const list: any[] = await this.resourceRep
            .createQueryBuilder('r')
            .select('IFNULL(MAX(r.sort),0) num')
            .where('r.videoId = :id and r.sourceType = :type', { id: dto.videoId, type: dto.sourceType })
            .execute();
        dto.sort = list[0]['num'] + 1;
        return this.resourceRep.save(dto);
    }

}
